<template>
	<div class="add-content">
		<list-title :data="header"></list-title>
		<el-form :model="goodsForm" :rules="rules" ref="goodsForm" label-width="150px">
			<el-form-item label="鉴品名称" prop="data.name" style="width: 830px;">
				<el-input v-model="goodsForm.data.name" placeholder="鉴品名称" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="所属栏目(可多选)" prop="parentid">
				<el-select v-model="goodsForm.parentid" filterable placeholder="请选择栏目" @change="chooseCategory" style="width: 334px">
					<el-option label="顶级栏目" value="0"></el-option>
					<el-option v-for="(item, index) in categoryList" 
					:key="index" 
					:label="item.name" 
					:value="item.catid"
					:disabled="checkCatidsRepeat(item.catid)">
					</el-option>
				</el-select>
				<ul class="category" v-if="goodsForm.data.catids.length > 0">
					<li v-for="(item, index) in goodsForm.data.catids" :key="index">
						<span>{{ item.name }}</span>
						<i @click="removeCategory(index)">×</i>
					</li>
				</ul>
			</el-form-item>
			<el-form-item label="预览图" prop="data.preview" style="width: 600px;">
				<upload-oss 
				:stsdomain="this.$domain.ac" 
				:ossdomain="this.$ossdomain" 
				:limit="5" 
				:fileList="goodsForm.data.preview" 
				:maxSize="20" 
				@insertFile="insertFile"
				@delFile="delFile">
				</upload-oss>
			</el-form-item>
			<el-form-item label="描述" prop="data.desc" style="width: 820px;">
				<el-input type="textarea" :rows="3" placeholder="请输入描述" v-model="goodsForm.data.desc"></el-input>
			</el-form-item>
			<el-form-item label="朝代" prop="data.dynasty" style="width: 830px;">
				<el-input v-model="goodsForm.data.dynasty" placeholder="朝代" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="长度" prop="data.long" style="width: 830px;" v-if="showAttr('long', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.long" placeholder="长度" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="宽度" prop="data.wide" style="width: 830px;" v-if="showAttr('wide', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.wide" placeholder="宽度" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="高度" prop="data.high" style="width: 830px;" v-if="showAttr('high', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.high" placeholder="高度" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="厚度" prop="data.thick" style="width: 830px;" v-if="showAttr('thick', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.thick" placeholder="厚度" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="直径" prop="data.diameter" style="width: 830px;" v-if="showAttr('diameter', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.diameter" placeholder="直径" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="重量" prop="data.weight" style="width: 830px;" v-if="showAttr('weight', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.weight" placeholder="重量" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="材质" prop="data.material" style="width: 830px;" v-if="showAttr('material', goodsForm.data.catid)">
				<el-input v-model="goodsForm.data.material" placeholder="材质" style="width: 334px"></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="data.state">
				<template>
					<el-radio v-model="goodsForm.data.state" label="1">备案成功</el-radio>
					<el-radio v-model="goodsForm.data.state" label="2">待备案</el-radio>
					<el-radio v-model="goodsForm.data.state" label="3">备案中</el-radio>
					<el-radio v-model="goodsForm.data.state" label="4">备案失败</el-radio>
				</template>
			</el-form-item>
			<el-form-item label="失败原因" prop="data.fail_reason" style="width: 830px;" v-if="goodsForm.data.state == 4">
				<el-input type="textarea" :rows="3" placeholder="请输入失败原因" v-model="goodsForm.data.fail_reason"></el-input>
			</el-form-item>
			<el-form-item label="添加时间" prop="data.add_time" style="width: 350px;">
				<el-date-picker
				v-model="goodsForm.data.add_time"
				format="yyyy-MM-dd HH:mm:ss"
				value-format="yyyy-MM-dd HH:mm:ss"
				type="datetime"
				placeholder="选择日期时间">
				</el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" plain @click="submitForm('goodsForm', '23')" :disabled='goodsForm.submitLock'>
					保存 <span class="el-icon-loading" v-if='goodsForm.submitLock'></span>
				</el-button>
				<el-button @click="resetForm('goodsForm')" v-if='goodsForm.data.id==0'>重 置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import UploadOss from "pc/common/UploadOss"
import {changeToBool, changeUploadFormatBack} from "static/js/common.js"

export default {
	inject: ['reload'],
	data() {
		return {
			/*栏目ID*/
			catid: this.$route.query.catid,
			/*头部数据*/
			header: {
				title: '添加内容',
				reload: false,
				buttons: [
					{
						title: '内容列表',
						type: 'primary',
						pathName: 'pc/epi/pj8/GoodsList',
						query: {
							catid: this.$route.query.catid,
							flag: this.$route.query.flag,
						},
					}
				]
			},
			categoryList: [],//所有栏目，便于选择
			goodsForm: {
				submitLock: false,
				parentid: '',//选择的栏目ID
				data: {
					id: 0,
					catid: 0,
					catids: [
						// {
						// 	'catid': 1,
						// 	'name': '国内新闻',
						// }
					],
					member_id: 0,
					name: '',
					dynasty: '',
					long: '',
					wide: '',
					high: '',
					thick: '',
					diameter: '',
					weight: '',
					material: '',
					desc: '',
					preview: [],
					state: '2',
					fail_reason: '',
					pass_time: '',
					add_time: '',
				},
				catids: "",//主要是为了获取修改数据的时候，能够放到 goodsForm.data.catids 的默认值中
				modifyData: false,//判断修改数据是否成功获取，true说明获取成功,防止监听重复操作
				modifyData2: false//判断修改数据是否成功获取，true说明获取成功,防止监听重复操作
			},
			rules: {
				data: {
					catids: [
						{ required: true, message: '请选择栏目', trigger: 'change' }
					],
					name: [
						{ required: true, message: '请输入鉴品名称', trigger: 'blur' },
						{ min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur' }
					]
				},
			},
			ueditor: {
				config: {}
			},
			
		};
	},
	components: {
		ListTitle,
		UploadOss
	},
	created: function() {

		/*取出分类列表*/
		this.getGoodsCategoryList()
		/*判断是否是单页，如果单页，去掉 标题栏的列表按钮*/
		if(this.$route.query.flag == 1){
			this.header.title = '编辑内容'
			// this.header.buttons = [] 注释原因：单页的话，也需要 列表 按钮，就当是 返回 作用
		}
		if(this.$route.query.flag == 1 && this.$route.query.id == undefined){
			/*请求旧数据*/
			this.getContent()
		}
		/*如果是修改，取出旧数据*/
		if(this.$route.query.id){
			this.getContent(this.$route.query.id)
		}
	},
	methods: {
		/*获取栏目*/
		getGoodsCategoryList: function(){
			if(this.$api.goodsCategoryList != undefined){
				this.$get(this.$api.goodsCategoryList).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = []
							Object.keys(res.data.data).forEach((k) => {
								let indent = '';
								for(var i=1; i<res.data.data[k].level; i++){
									if(i == 1){
										indent += '|---';
									}else{
										indent += '---';
									}
								}
								this.categoryList.push ({
									catid: res.data.data[k].catid,
									name: indent + res.data.data[k].name
								});
								/*添加默认的分类，此分类不能删*/
								if(this.$route.query.catid == res.data.data[k].catid){
									this.goodsForm.data.catids.push(
										{
											'catid': res.data.data[k].catid,
											'name': res.data.data[k].name,
										}
									)
								}
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*选择栏目*/
		chooseCategory: function(val){
			/*遍历categoryList，找出选择的字段*/
			let obj = this.categoryList.find((item)=>{
				return item.catid === val;
			});
			let getName = obj.name;
			getName = getName.replace(/^\|\-+/,"");

			/*goodsForm.data.catids里排重，不重复的就添加*/
			let has = false
			this.goodsForm.data.catids.forEach((item, index) => {
				if(item.catid == val){
					has = true
				}
			})

			if(!has){
				this.goodsForm.data.catids.push(
					{
						'catid': val,
						'name': getName,
					}
				)
			}
			this.goodsForm.parentid = ''//选择内容清除，便于再次选择
		},
		/*删除栏目*/
		removeCategory(index) {
			if(this.goodsForm.data.catids[index].catid == this.$route.query.catid){//如果是默认分类，不能删
				this.$message({
					showClose: true,
					message: '默认分类，不能删除',
					type: 'error'
				});
			}else{
				this.goodsForm.data.catids.splice(index, 1);
			}
		},
		/*
		提交添加、修改表单
		*/
		submitForm(formName, flag) {
			if(!this.goodsForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {

						this.goodsForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addGoods//默认是添加
						if(this.goodsForm.data.id > 0){//修改
							apiUrl = this.$api.modifyGoods
						}
						// let data = this.goodsForm.data
						let data = JSON.parse(JSON.stringify(this.goodsForm.data))

						if(data.content != undefined && data.preview.length == 0){
							data.preview = null
						}
						// console.log(data, 'aaaa')
						// return

						/*添加、修改内容*/
						if(apiUrl != undefined){
							this.$post(apiUrl, {
								Goods: data
							}).then(res => {
								// console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});
									if(this.goodsForm.data.id > 0 || this.$route.query.flag == 1){//当是添加 或 单页 的时候
										this.$router.go(-1)	
									}else{
										this.$refs[formName].resetFields();
										this.getGoodsCategoryList();
										this.goodsForm.data.catids = []
									}
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.goodsForm.submitLock = false;
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*重置表单*/
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.$refs.ue.setUEContentEmpty()//清空ueditor内容
		},
		/*插入上传的图片*/
		// insertPic(list, field){
		// 	for(let i=0; i<list.length; i++){
		// 		this.goodsForm.data[field].push(
		// 			{
		// 				name: '',
		// 				url:  list[i].url
		// 			}
		// 		)
		// 	}
		// },
		/*删除上传的图片*/
		// delPic(index, field){
		// 	this.goodsForm.data[field].splice(index, 1)
		// },
		/*插入上传的文件*/
		insertFile(file, field){
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				for(let i=0; i<file.length; i++){
					this.goodsForm.data.preview.push(
						{
							name: '',
							url:  file[i].url
						}
					)
				}
			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delFile(index){
			if(index >= 0){//图片
				this.goodsForm.data.preview.splice(index, 1)
			}else{//文件路径

			}
		},
		/*取出需要修改的数据*/
		getContent: function(){
			if(this.$api.modifyGoods != undefined){	
				this.header.title = '编辑内容'
				/*取出需要修改的数据*/
				this.goodsForm.submitLock = true;
				this.$get(this.$api.modifyGoods, {
					'id': this.$route.query.id,
					'catid': this.$route.query.catid
				}).then(res => {
					if(res.data.code == 0){
						if(res.data.data.goods){
							this.goodsForm.data.id = res.data.data.goods.goods_id
							this.goodsForm.data.catid = res.data.data.goods.catid
							this.goodsForm.data.member_id = res.data.data.goods.member_id
							this.goodsForm.data.name = res.data.data.goods.name
							this.goodsForm.data.dynasty = res.data.data.goods.dynasty
							this.goodsForm.data.long = res.data.data.goods.long
							this.goodsForm.data.wide = res.data.data.goods.wide
							this.goodsForm.data.high = res.data.data.goods.high
							this.goodsForm.data.thick = res.data.data.goods.thick
							this.goodsForm.data.diameter = res.data.data.goods.diameter
							this.goodsForm.data.weight = res.data.data.goods.weight
							this.goodsForm.data.material = res.data.data.goods.material
							this.goodsForm.data.desc = res.data.data.goods.desc
							this.goodsForm.data.preview = changeUploadFormatBack(res.data.data.goods.preview)
							this.goodsForm.data.state = res.data.data.goods.state
							this.goodsForm.data.fail_reason = res.data.data.goods.fail_reason
							this.goodsForm.data.pass_time = res.data.data.goods.pass_time
							this.goodsForm.data.add_time = res.data.data.goods.add_time

							this.goodsForm.catids = res.data.data.goods.catids
						}

					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
					this.goodsForm.submitLock = false;
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
	},
	watch: {
		/*监听categoryList, goodsForm连个参数，为了把老的所属分类放上去*/
		modifyCategoryData: {
			handler: function(val) {
				// console.log(val.categoryList, 'fff')
				if(!this.modifyData2 && val.categoryList != '' && val.goodsForm.catids != ''){
					this.modifyData2 = true
					// console.log(val.goodsForm.catids, 'dd')
					let tmpArr = val.goodsForm.catids.split(',')
					// console.log(tmpArr)
					this.goodsForm.data.catids = []

					Object.keys(tmpArr).forEach((k) => {
						Object.keys(val.categoryList).forEach((k1) => {
							if(val.categoryList[k1].catid == tmpArr[k]){
								// console.log(val.categoryList[k1].catid)
								this.goodsForm.data.catids.push(
									{
										'catid': val.categoryList[k1].catid,
										'name': val.categoryList[k1].name.replace(/^\|\-+/,""),
									}
								)
							}
						})
					})
				}
			},
			deep: true
		}
	},
    computed: {
    	/*验证 所属分类 是否已经选择了，不能再选*/
		checkCatidsRepeat(val) {
			return function (val) {
				let has = false
				this.goodsForm.data.catids.find((item) => {
					if(val == item.catid){
						has = true
					}
				})
				return (has)
			}
		},
		/*监听categoryList, goodsForm连个参数，为了把老的所属分类放上去*/
		modifyCategoryData() {
			const {categoryList, goodsForm} = this
			return {
				categoryList,
				goodsForm
			}
		},
		/*属性显示*/
		showAttr(attr, catid) {
			return function (attr, catid) {
				// console.log(attr, 222);
				// console.log(catid, 333);
				let arr1 = ['long', 'wide', 'high']//瓷器
				let arr2 = ['diameter', 'weight', 'material']//钱币
				let arr3 = ['long', 'wide', 'high', 'weight', 'material']//明清铜器
				let arr4 = ['long', 'wide']//书画
				let arr5 = ['long', 'wide', 'thick', 'weight', 'material']//铜镜
				let arr6 = ['long', 'wide', 'high', 'material']//明清家具
				let arr7 = ['long', 'wide', 'high', 'weight', 'material']//佛像
				let arr8 = ['long', 'wide', 'high']//古籍
				let arr9 = ['weight']//老酒
				let arr10 = ['long', 'wide', 'high', 'material']//玉器
				for(let i = 0; i < this.categoryList.length; i++) {
					if(catid == this.categoryList[i].catid && catid > 10) {
						catid = this.categoryList[i].parentid
					}
				}

				/*遍历分类 如果parentid 有对应的ID，改变catid*/
				for(let i = 0; i < this.categoryList.length; i++) {
					if(this.categoryList[i].parentid == catid) {
						catid = this.categoryList[i].catid
						break
					}
				}
				let show = false
				switch(catid) {
					case '1'://瓷器
						if(arr1.indexOf(attr) > -1) {
							// console.log(show, 456)
							show = true;
						}
						break;
					case '2'://钱币
						if(arr2.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '3'://明清铜器
						if(arr3.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '4'://书画
						if(arr4.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '5'://铜镜
						if(arr5.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '6'://明清家具
						if(arr6.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '7'://佛像
						if(arr7.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '8'://古籍
						if(arr8.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '9'://老酒
						if(arr9.indexOf(attr) > -1) {
							show = true;
						}
						break;
					case '10'://玉器
						if(arr10.indexOf(attr) > -1) {
							show = true;
						}
						break;
				}
				// console.log(show, 123)
				return show;
			}
		}
    }
};
</script>

<style lang="stylus" scoped>
.add-content
	form
		margin-top: 10px
		.el-color-picker
			margin-left: 10px
			position: absolute
		.category,.tag
			// border: red 1px solid
			padding-top: 10px
			width: 453px
			overflow: hidden
			li
				float: left
				border: #d6d6d6 1px solid
				margin-right: 10px
				margin-bottom: 10px
				cursor: pointer
				position: relative
				span
					display: block
					padding: 0 10px
					height: 100%
					font-size: 12px
		 	li:hover i
				display: block
			li
				i
					width: 18px
					height: 18px
					line-height: 18px
					font-style: normal
					text-align: center
					color: #fff
					position: absolute
					display: inline-block
					border-radius: 100%
					background-color: rgba(0, 0, 0, .5)
					top: -9px
					right: -9px
					display: none
			li
				i:hover
					background-color: rgba(0, 0, 0, 1)
		.tag-lib
			border: #4abadb 1px solid
			padding: 0 10px
			overflow: hidden
			li
				float: left
				cursor: pointer
				padding: 0px
				// border: red 1px solid
				margin-right: 10px
				span
					font-size: 12px
			li:hover
				color: #4abadb
	/*Ueditor行高有问题*/
	/deep/ .edui-default .edui-toolbar .edui-combox .edui-combox-body
			line-height: 20px !important
	/deep/ .edui-default .edui-button-body
			line-height: 20px !important
	/deep/ .edui-splitbutton-body
			line-height: 20px !important
	/deep/ .edui-menubutton-body
			line-height: 20px !important
	/*Ueditor 下拉箭头偏右*/
	/deep/ .edui-default .edui-toolbar .edui-combox-body .edui-arrow
			background-position: -742px 0px
</style>